import React, { Component } from 'react';  
import {  
  StyleSheet,  
  View,  
  Text,  
  Image,
  Animated,
  Easing,
  TouchableOpacity,
} from 'react-native';  
import {
    GREEN_COLOR, WHITE_COLOR, BLACK_COLOR, 
    FONT_SIZE_16, FONT_SIZE_14, YELLOW_COLOR, CONTENT_BACK_COLOR} from './config';
import UIButton from './UIButton';

import { BOX_LINE_COLOR } from './type';

// //使用说明
// id: 101 为取消按钮 如果id小于0则点击按钮后不隐藏按钮
// if (this.refs_UIAlert) {
//   this.refs_UIAlert.showV( {
//       title: "title",//通知标题
//       text: "text",//内容
//       /****
//        * 
//        * buttons : [item，[item,item,item]]//内部可以是oject（）或者array（一行多个）
//        * 
//        * item : {
//        *      title : 按钮文案
//        *      titleColor : 文字颜色
//        *      backgroundColor : 按钮背景色
//        *      id : 区分回调
//        * }
//        * 
//        * 
//        */
//       buttons: [{
//           title: "b1",
//           titleColor: WHITE_COLOR,
//           backgroundColor: YELLOW_COLOR,
//           id:1, // 101 为取消按钮 
//         },[{
//           title: "b1",
//           titleColor: WHITE_COLOR,
//           backgroundColor: YELLOW_COLOR,
//           id:1
//         },{
//           title: "b2",
//           titleColor: WHITE_COLOR,
//           backgroundColor: YELLOW_COLOR,
//           id:2
//       },{
//           title: "b3",
//           titleColor: WHITE_COLOR,
//           backgroundColor: YELLOW_COLOR,
//           id:2
//       }]]
//   } )
// }

let defaultStr = {
  BCancel : "取消",
  BOk : "确定",
  title : "通知",
  BClose : "关闭"
}
export default class UIAlert extends Component {  

  constructor(props) {  
    super();  
    let buttons = [{
      title: defaultStr.BCancel,
      titleColor: WHITE_COLOR,
      backgroundColor: YELLOW_COLOR,
      id:1
    },{
      title: defaultStr.BOk,
      titleColor: WHITE_COLOR,
      backgroundColor: GREEN_COLOR,
      id:2
    }];
    
    this.state = {
        title: (props.myData && props.myData.title) ? props.myData.title : defaultStr.title,
        text: (props.myData && props.myData.text) ? props.myData.text : defaultStr.title,
        buttons: (props.myData && props.myData.buttons) ? props.myData.buttons : buttons,
        isSubB: !props.isSubB ? true : false,
        shouAin:new Animated.Value(0),
      };
  }  
  UNSAFE_componentWillMount(){
    this.mounted = true;
  }
  componentWillUnmount(){
    this.mounted = false;
  }
   // 获取最新的Props 并修改该原有的值
   UNSAFE_componentWillReceiveProps(nextProps){
    if (this.mounted) {
      if (nextProps.myData && (this.state.title != nextProps.myData.title || this.state.text != nextProps.myData.text || this.state.buttons != nextProps.myData.buttons)) {
        this.setState({
          title : (nextProps.myData.title != this.state.title) ? nextProps.myData.title : this.state.title,
          text : (nextProps.myData.text != this.state.text) ? nextProps.myData.text : this.state.text,
          buttons : (nextProps.myData.buttons != this.state.buttons) ? nextProps.myData.buttons : this.state.buttons,
        })
      }
    }
  }
  createButtons( array, key2 ){
    let buttonArr = []
    if (!key2) {
      key2 = "key";
    }
    if (Object.prototype.toString.call(array) === '[object Array]') {
      for (const key in array) {
        if (array.hasOwnProperty(key)) {
          const element = array[key];
          if (Object.prototype.toString.call(element) === '[object Object]') {
            buttonArr.push(this.button( element, `${key2}`, key))

          }else if (Object.prototype.toString.call(element) === '[object Array]') {
            buttonArr.push( <View key={`${key2}${key}`} style = {[styles.tipTitleView, { borderTopWidth: 0, borderBottomWidth:0, paddingTop:10, paddingBottom : 5 } ]}>{this.createButtons( element, `${key2}${key}`, key)}</View>) 
          }
        }
      }
    }
    return buttonArr;
  }
  button( element, key, index  ){
   
    return <Button key = {`key${index}`} myKey = {key} data = {element} cancel = {this.cancel.bind(this)}/>
  }
  render() {  
      const {
        title,
        text,
    } = this.state
      return (  
        <Animated.View style={[styles.subViewStyle,{elevation : 2}, this.dispalayPosition(this.state.isSubB)]} >
            <View style={[styles.subViewStyle,{position:"absolute", backgroundColor:BLACK_COLOR,opacity:0.6}]}>
            </View>
            <Animated.View style={[styles.container,{ transform:[
                {
                    scale:this.state.shouAin
                }]}]}>
                <View style = {{ alignItems: 'flex-start',  borderBottomWidth: 1, borderColor: BOX_LINE_COLOR, marginHorizontal: 5}} >

                  <View style={ [styles.tipTitleView, ] } >  
                      <Text allowFontScaling={false} style={styles.titleText}>{title}</Text>
                      {/* <Text allowFontScaling={false} style={styles.closeText} onPress={this.cancel.bind(this)} >{defaultStr.BClose}</Text>   */}
                      <TouchableOpacity
                        style = {{ }}
                        activeOpacity = {1}
                        onPress = {this.cancel.bind(this, 101)}>
                        <Image 
                          source = {this.state.imgurl? {uri:this.state.imgurl}:require('../image/close3.png')}
                          resizeMode = {'contain'}
                          style = {{ width: 15, height: 15}}/>
                      </TouchableOpacity>
                  </View> 
                  <Text allowFontScaling={false} style = {[styles.contentText,{ marginTop: 15, marginBottom: 30, lineHeight: 25},this.props.contentText?this.props.contentText:{}]}>{text}</Text>             
                </View>
                
                <View style={{ width:'100%' }} > 
                  { this.state.isSubB ? null : this.createButtons(this.state.buttons) }
                </View>
            </Animated.View>  
        </Animated.View>
        
      );  
    
  }  
  
  showV(myData){
    //重置buttons data
    if (myData && (this.state.title != myData.title || this.state.text != myData.text || this.state.buttons != myData.buttons)) {
      this.state.title = (myData.title && (myData.title != this.state.title) ) ? myData.title : this.state.title;
      this.state.text = (myData.text && (myData.text != this.state.text) ) ? myData.text : this.state.text;
      this.state.buttons = (myData.buttons && (myData.buttons != this.state.buttons) ) ? myData.buttons : this.state.buttons
     
    }
    if(this.state.isSubB){
      window.requestAnimationFrame(()=>{
        this.state.shouAin.setValue(0.5)
        Animated.timing(this.state.shouAin,{
          toValue : 1,
          duration : 500, 
          easing : Easing.bezier(0.16, 1, 0.3, 1),
          useNativeDriver: false
      }).start();
      })
    }
    
    this.setState({
        isSubB: false
    })
  }
  heiV(){
    this.setState({
        isSubB: true
    })
  }
  cancel(tagId,data){
    
    this.props.clickBtn && this.props.clickBtn(tagId, data?data:{});
    if (Object.prototype.toString.call(tagId) != '[object Number]' || tagId >= 0) {
      this.heiV()
    }
  }
  //0.54之后出现 position:'absolute' 同时使用 display 属性则会出现display失效
  dispalayPosition = ( status )=>{
    return {
        display:status ? 'none' : 'flex',
        position:status ? 'relative' : 'absolute',
    }
  }

}
class Button extends Component{
  constructor( props ){
    super()
    this.buttonState = {
      data : props.data ? props.data : {},
      myKey : props.myKey,
    }
  }
  UNSAFE_componentWillReceiveProps(nextProps){
    this.buttonState.data = nextProps.data ? nextProps.data : {}
    this.buttonState.myKey = nextProps.myKey
  }
  render(){
    const {
      title, 
      titleColor, 
      backgroundColor, 
      id,
    } = this.buttonState.data;

    return (<View style={{flex: (this.buttonState.myKey == 'key')?0:1, margin:5, height:35, display:title?'flex':'none'}}>
              <UIButton
                  name = { title }
                  tagId = {id}
                  onPress={(tagId)=>{
                    this.props.cancel && this.props.cancel(tagId,this.buttonState.data);
                      
                  }}
                  styles={{
                      backgroundColor:backgroundColor,
                      borderRadius:5,
                      fontSize:12,
                      titleColor:titleColor
                  }}
              />
              </View> )
  }
}
const styles = StyleSheet.create({  
  container: {  
    overflow: 'hidden',
    alignItems: 'center', 
    justifyContent: 'space-around',
    padding: 10,
    borderRadius: 5,
    backgroundColor: CONTENT_BACK_COLOR,
  },   
  tipTitleView: {  
    flexDirection: 'row',  
    alignItems: 'center', 
    paddingVertical: 5,
    paddingBottom: 10, 
    borderColor: BOX_LINE_COLOR, 
    borderBottomWidth: 1,
  },  
  closeText: {  
    color: GREEN_COLOR,  
    fontSize: FONT_SIZE_14,  
    padding: 5,
  },  
 
  subViewStyle: {  
    padding: 20,
    justifyContent: 'center',
    right: 0,
    bottom: 0,
    left: 0,  
    top: 0,  
  },
  titleText: {
    flex: 1,
    color: BLACK_COLOR,
    fontWeight: "bold",
    fontSize: FONT_SIZE_16,
    textAlign: 'left',
    // marginLeft:30
  },
  contentText: {
      paddingVertical: 5,
      // paddingHorizontal: 5,
      fontSize: FONT_SIZE_14,
      textAlign: 'left',
      color: BLACK_COLOR,
  }
});  